package com.tianqingwl.gsystem.content.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianqingwl.gsystem.common.enumeration.SysConfigConstants;
import com.tianqingwl.gsystem.common.vo.CommonResultVo;
import com.tianqingwl.gsystem.content.mapper.ContentInfoMapper;
import com.tianqingwl.gsystem.content.mapper.ContentTypeMapper;
import com.tianqingwl.gsystem.content.param.ContentInfoQueryParam;
import com.tianqingwl.gsystem.content.pojo.ContentInfo;
import com.tianqingwl.gsystem.content.pojo.ContentType;
import com.tianqingwl.gsystem.content.service.ContentInfoService;
import com.tianqingwl.gsystem.content.service.ContentTypeService;
import com.tianqingwl.gsystem.resources.pojo.SysConfig;
import com.tianqingwl.gsystem.resources.service.SysConfigService;
import com.tianqingwl.gsystem.sysuser.pojo.SysUser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ContentInfoServiceImpl implements ContentInfoService {

    @Autowired
    private ContentInfoMapper contentInfoMapper;
    @Autowired
    private ContentTypeMapper contentTypeMapper;
    @Autowired
    private ContentTypeService contentTypeService;
    @Autowired
    private SysConfigService sysConfigService;

    @Override
    public boolean haveContentByTypeId(Long contentTypeId) {
        int count = contentInfoMapper.selectCount(new QueryWrapper<ContentInfo>().eq("contentType", contentTypeId));
        return count > 0;
    }

    @Override
    public void list(Page<ContentInfo> contentPage, ContentInfoQueryParam queryParam) {
        QueryWrapper<ContentInfo> queryWrapper = new QueryWrapper<>();
        if (queryParam != null) {
            if (!StringUtils.isEmpty(queryParam.getContentTitle())) {
                queryWrapper.like("contentTitle", queryParam.getContentTitle());
            }
            if (!StringUtils.isEmpty(queryParam.getContentTypeName())) {
                queryWrapper.like("contentTypeName", queryParam.getContentTypeName());
            }
            if (!StringUtils.isEmpty(queryParam.getUserShowName())) {
                queryWrapper.like("userShowName", queryParam.getUserShowName());
            }
            if (queryParam.getUserId() != null) {
                queryWrapper.eq("userId", queryParam.getUserId());
            }
            if (queryParam.getStatus() != null) {
                queryWrapper.eq("status", queryParam.getStatus());
            }
            if (queryParam.getCreateStartTime() != null) {
                queryWrapper.ge("createTime", queryParam.getCreateStartTime());
            }
            if (queryParam.getCreateEndTime() != null) {
                queryWrapper.ge("createTime", queryParam.getCreateEndTime());
            }

            if (queryParam.getOrderBy() != null) {
                queryWrapper.orderBy(true, queryParam.isAsc(), queryParam.getOrderBy());
            }
//            queryWrapper.orderByDesc("createTime");


            if (queryParam.getType() != null) {
                if (queryParam.getType() == 1 && queryParam.getContentType() != null) {//类别
                    queryWrapper.eq("contentType", queryParam.getContentType());
                } else if (queryParam.getType() == 2) {
                    //关联标签关系查询
                    queryWrapper.select("*");
                    if (queryParam.getContentType() != null) {
                        queryWrapper.eq("tagId", queryParam.getContentType());
                    }
                    contentInfoMapper.listContentTagPage(contentPage, queryWrapper);
                    return;
                }
            }
        } else {
            queryWrapper.orderByDesc("createTime");
        }
        contentInfoMapper.selectPage(contentPage, queryWrapper);
    }

    @Transactional
    @Override
    public void save(ContentInfo contentInfo) {
        SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (contentInfo == null) {
            return;
        }

        if (contentInfo.getContentId() == null) {
            //新增
            //封面
            if (StringUtils.isEmpty(contentInfo.getCover())) {
                //随机获取从配置中
                List<SysConfig> coverList = sysConfigService.getSysConfigByKey("defaultCover");
                if (CollectionUtil.isEmpty(coverList)) {
                    contentInfo.setCover("/upload/defaultCover.jpg");//默认图片
                } else {
                    int index = RandomUtil.randomInt(0, coverList.size());
                    SysConfig sysConfig = coverList.get(index);
                    contentInfo.setCover(sysConfig.getConfigValue());
                }
            }
            Document contentDoc = Jsoup.parse(contentInfo.getContentInfo());
            String contentText = contentDoc.text();
            if (StringUtils.isEmpty(contentText) || contentText.length() < 50) {
                throw new RuntimeException("内容字数不能小于50");
            }
            //摘要提取
            if (StringUtils.isEmpty(contentInfo.getDescription())) {
                contentInfo.setDescription(contentText.substring(0, 50));
            }
            //TODO 关键词提取,暂时不自动提取目前没有较好的方案
            if (StringUtils.isEmpty(contentInfo.getKeywords())) {

            }
            //初始数据
            contentInfo.setUserId(sysUser.getUserId());
            contentInfo.setUserShowName(sysUser.getShowName());
            contentInfo.setCreateTime(new Date());
            if (contentInfo.getContentType() == null) {
                throw new RuntimeException("需要选择一个类别");
            }
            ContentType contentType = contentTypeService.getContentTypeById(contentInfo.getContentType());
            if (contentType == null) {
                throw new RuntimeException("illegal typeId");
            }
            contentInfo.setContentTypeName(contentType.getTypeName());
            contentInfoMapper.insert(contentInfo);
        } else {
            //修改
            //非修改项
            contentInfo.setUserId(null);
            contentInfo.setUserShowName(null);
            contentInfo.setCreateTime(null);
            contentInfo.setUpdateTime(new Date());
            if (contentInfo.getContentType() != null) {
                ContentType contentType = contentTypeService.getContentTypeById(contentInfo.getContentType());
                if (contentType == null) {
                    throw new RuntimeException("illegal typeId");
                }
                contentInfo.setContentTypeName(contentType.getTypeName());
            }

            contentInfoMapper.updateById(contentInfo);
        }


        //更新标签
        //先删后加
        contentTypeMapper.deleteContentTagRelateByContentId(contentInfo.getContentId());
        List<Long> tagIds = findAndCreateTag(contentInfo.getTagNames());
        if (tagIds != null && tagIds.size() > 0) {
            contentTypeMapper.addContentTagRelate(contentInfo.getContentId(), tagIds);
        }
    }

    /**
     * 没有则创建标签
     *
     * @param tagNames
     * @return
     */
    private List<Long> findAndCreateTag(List<String> tagNames) {
        List<Long> ids = new ArrayList<>();
        if (tagNames != null && tagNames.size() > 0) {
            for (String tagName : tagNames) {
                if (!StringUtils.isEmpty(tagName) && tagName.trim().length() > 0) {
                    ContentType tag = contentTypeMapper.selectTagByName(tagName);
                    if (tag == null) {
                        tag = new ContentType();
                        tag.setTypeName(tagName);
                        tag.setType(2);
                        contentTypeMapper.insert(tag);
                    }
                    ids.add(tag.getTypeId());
                }
            }
        }
        return ids;
    }

    @Override
    public ContentInfo getContentInfoById(Long contentId) {
        return contentInfoMapper.selectById(contentId);
    }

    @Override
    public void deleteById(Long contentId) {
        contentInfoMapper.deleteById(contentId);
    }

    @Override
    public void deleteByIdList(List<Long> idList) {
        for (Long id : idList) {
            deleteById(id);
        }
    }

    @Override
    public List<ContentInfo> listHotContent() {
        QueryWrapper<ContentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",1);
        queryWrapper.orderByDesc("viewCount");
        queryWrapper.last("limit 10");
        List<ContentInfo> contentInfos = contentInfoMapper.selectList(queryWrapper);
        return contentInfos;
    }

    /**
     * 推荐同类别阅读量最高的10篇文章
     *
     * @param contentType
     * @return
     */
    @Override
    public List<ContentInfo> listRecommendContent(Long contentType) {
        QueryWrapper<ContentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contentType", contentType);
        queryWrapper.eq("status", 1);
        queryWrapper.orderByDesc("viewCount");
        queryWrapper.last("limit 10");
        List<ContentInfo> contentInfos = contentInfoMapper.selectList(queryWrapper);
        return contentInfos;
    }

    @Override
    public List<ContentInfo> nearContentList(Long contentId) {
        List<ContentInfo> contentInfoList = contentInfoMapper.selectNearContent(contentId);
        ContentInfo temp = new ContentInfo();
        temp.setContentTitle("没有了");
        if (contentInfoList == null || contentInfoList.size() < 1) {
            contentInfoList.add(temp);
            contentInfoList.add(temp);

        } else {
            if (contentInfoList.size() == 1) {
                //判断是否大于决定位置
                ContentInfo contentInfo = contentInfoList.get(0);
                if (contentInfo.getContentId() > contentId) {
                    contentInfoList.add(0, temp);
                } else {
                    contentInfoList.add(temp);
                }
            }
        }

        return contentInfoList;
    }

    @Override
    public void updateViewCount(Long contentId) {
        contentInfoMapper.updateViewCount(contentId);
    }

    @Override
    public void updateUserShowName(Long userId, String showName) {
        ContentInfo contentInfo = new ContentInfo();
        contentInfo.setUserId(userId);
        contentInfo.setUserShowName(showName);
        QueryWrapper<ContentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        contentInfoMapper.update(contentInfo, queryWrapper);
    }

    @Override
    public CommonResultVo baiduSubmit(Long contentId, Long[] contentIds) {
        List<SysConfig> sysConfigByGroup = sysConfigService.getSysConfigByGroup(SysConfigConstants.Group.baidu_submit);
        SysConfig siteConfig = sysConfigService.getSysConfig(SysConfigConstants.Group.site_config, SysConfigConstants.Key.domain);
        StringBuffer url = new StringBuffer();
        //url
        for (SysConfig sysConfig : sysConfigByGroup) {
            if (SysConfigConstants.Key.url.equals(sysConfig.getConfigKey())) {
                url.append(sysConfig.getConfigValue());
                break;
            }
        }
        //site
        for (SysConfig sysConfig : sysConfigByGroup) {
            if (SysConfigConstants.Key.site.equals(sysConfig.getConfigKey())) {
                url.append("?site=" + sysConfig.getConfigValue());
                break;
            }
        }
        //token
        for (SysConfig sysConfig : sysConfigByGroup) {
            if (SysConfigConstants.Key.token.equals(sysConfig.getConfigKey())) {
                url.append("&token=" + sysConfig.getConfigValue());
                break;
            }
        }
        //生成文章urls
        StringBuffer postUrls = new StringBuffer();
        if (contentId!=null){
            postUrls.append(siteConfig.getConfigValue() + "/" + contentId + ".html\r\n");
        }else if(contentIds!=null&&contentIds.length>0){
            for (Long id : contentIds) {
                postUrls.append(siteConfig.getConfigValue() + "/" + id + ".html\r\n");
            }
        }
        String post = HttpUtil.post(url.toString(), postUrls.toString());
        return CommonResultVo.success(post);
    }

    @Override
    public void search(Page<ContentInfo> searchPage, String searchContent) {
        //TODO 以后改造成 lucene
        if (StringUtils.isEmpty(searchContent)){
            return;
        }
        QueryWrapper<ContentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .like("contentTitle", searchContent);
        queryWrapper.eq("status",1);
        contentInfoMapper.selectPage(searchPage, queryWrapper);
    }
}
